using Mono.Cecil;
using Mono.Cecil.Cil;

namespace Cil.Ast;

public sealed class ParameterGetExpression : SingleInstructionExpression
{
	public const int MaxNodes = 0;

	public ParameterGetExpression(Context context, Instruction position, ParameterReference ref_parameter)
		: base(context, position)
	{   
		if(ref_parameter.Index >= short.MaxValue) 
		{
			throw new ArgumentOutOfRangeException(string.Format("Method must not contain more than {0} parameters. Please, optimize your code.", short.MaxValue));
		}

		// base class
		ReadsStack = 0;
		WritesStack = 1;
		ReturnType = ref_parameter.ParameterType;
		Nodes = new FixedList<Expression>();

		// this
		ParameterReference = ref_parameter;
	}

	bool? _isThis;
	public bool IsThis 
	{
		get
		{
			if (!_isThis.HasValue)
			{
				_isThis = new bool?(ParameterReference.Index == -1);
			}
			return _isThis.Value;
		}
	}

	public ParameterReference ParameterReference  { get; private set; }

	public override string ToString()
	{
		return string.Format(IsThis ? "this": "{0}", ParameterReference);
	}
}

public static partial class IlAst
{
	public static ParameterGetExpression ParameterGet(Context context, Instruction position, ParameterReference ref_parameter)
	{
		return new ParameterGetExpression(context, position, ref_parameter);
	}
}